package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.dto.PreventionCheckTaskConfigRefreshDTO;
import com.ruoyi.system.domain.dto.PreventionHiddenDeptTreeListDTO;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.entity.*;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalTime;
import java.util.*;

/**
 * 双重预防-排查任务配置表(PreventionCheckTaskConfig)表服务实现类
 *
 * @since 2022-11-18 13:58:19
 */
@Slf4j
@Service("preventionCheckTaskConfigService")
public class PreventionCheckTaskConfigServiceImpl implements PreventionCheckTaskConfigService {
    @Resource
    private PreventionCheckTaskConfigMapper preventionCheckTaskConfigDao;
    @Resource
    private PreventionCheckTaskService preventionCheckTaskService;
    @Resource
    private PreventionCheckTaskMapper preventionCheckTaskMapper;
    @Resource
    private PreventionSecurityRiskService preventionSecurityRiskService;
    @Resource
    private SysActingService sysActingService;
    @Resource
    private ISysUserService userService;
    @Resource
    private PreventionAlertMapper preventionAlertMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private EnterpriseWXServiceImpl enterpriseWXService;
    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private PreventionSecurityRiskRefreshMapper preventionSecurityRiskRefreshMapper;
    @Resource
    private PreventionSecurityRiskMapper preventionSecurityRiskMapper;
    @Resource
    private PreventionUnitMapper preventionUnitMapper;


    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public PreventionCheckTaskConfig queryById(Integer id) {
        return this.preventionCheckTaskConfigDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @return 查询结果
     */
    @Override
    public List<PreventionCheckTaskConfigVO> queryByPage(PreventionCheckTaskConfigVO preventionCheckTaskConfigVO) {
        List<PreventionCheckTaskConfigVO> preventionCheckTaskConfigVOS = preventionCheckTaskConfigDao.queryAllByLimit(preventionCheckTaskConfigVO);
        preventionCheckTaskConfigVOS.forEach(i -> {
            Integer id = i.getId();
            PreventionCheckTask preventionCheckTask = preventionCheckTaskService.queryByConfigId(id);
            if (preventionCheckTask != null) {
                i.setTaskState(preventionCheckTask.getTaskState());
                i.setPreventionCheckTask(preventionCheckTask);
            } else {
                i.setTaskState("无任务");
            }
        });
        return preventionCheckTaskConfigVOS;
    }

    /**
     * 新增数据
     *
     * @param preventionCheckTaskConfig 实例对象
     * @return 实例对象
     */
    @Override
    public PreventionCheckTaskConfig insert(PreventionCheckTaskConfig preventionCheckTaskConfig) {
        this.preventionCheckTaskConfigDao.insert(preventionCheckTaskConfig);
        return preventionCheckTaskConfig;
    }

    /**
     * 修改数据
     *
     * @param preventionCheckTaskConfig 实例对象
     * @return 实例对象
     */
    @Override
    public PreventionCheckTaskConfig update(PreventionCheckTaskConfig preventionCheckTaskConfig) {
        this.preventionCheckTaskConfigDao.update(preventionCheckTaskConfig);
        return this.queryById(preventionCheckTaskConfig.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.preventionCheckTaskConfigDao.deleteById(id) > 0;
    }

    @Override
    public void insertBatch(List<PreventionCheckTaskConfig> preventionCheckTaskConfigList) {
        preventionCheckTaskConfigDao.insertBatch(preventionCheckTaskConfigList);
    }

    // @Scheduled(cron = "0/60 * * * * ?")
    public void scheduledConfigOne() {
        List<PreventionCheckTaskConfig> preventionCheckTaskConfigs = preventionCheckTaskConfigDao.queryAll();
        for (PreventionCheckTaskConfig i : preventionCheckTaskConfigs) {
            PreventionSecurityRisk preventionSecurityRisk = preventionSecurityRiskService.queryById(i.getSecurityRiskId());
            if (null == preventionSecurityRisk) {
                continue;
            }
          /*  PreventionUnit preventionUnit = preventionUnitMapper.queryByDeviceId(preventionSecurityRisk.getDeviceId());
            if (null != preventionUnit && preventionUnit.getState().equals("1")) {
                continue;
            }*/
            Integer whetherConfig = i.getWhetherConfig();
            // 是否发布
            Integer whetherRelease = i.getWhetherRelease();
            if (whetherConfig == 0 && whetherRelease == 0) {
                String taskStartTime = i.getTaskStartTime();
                DateTime parse = DateUtil.parse(taskStartTime, "yyyy-MM-dd HH:mm:ss");
                Date date = parse.toJdkDate();
                DateTime now = DateUtil.date();
                boolean after = date.after(now);
                if (!after) {
                    if (ObjectUtils.isNotEmpty(preventionSecurityRisk)) {
                        if (StringUtils.isNotEmpty(preventionSecurityRisk.getCycle())) {
                           /* String cycle = preventionSecurityRisk.getCycle();
                            // 小时 月 天 年
                            String unit = preventionSecurityRisk.getUnit();*/

                            PreventionCheckTask byConfigId = preventionCheckTaskService.queryByConfigId(i.getId());
                            /*PreventionCheckTask preventionCheckTask = new PreventionCheckTask();*/
                            if (byConfigId != null) {
                                String endTime = byConfigId.getEndTime();
                                DateTime dateTime = DateUtil.parse(endTime, "yyyy-MM-dd HH:mm:ss");
                                Date date1 = dateTime.toJdkDate();

                                Calendar calendar = new GregorianCalendar();
                                calendar.setTime(date1);
                                // 把日期往后增加一天,整数  往后推,负数往前移动
                                calendar.add(Calendar.DATE, -3);

                                boolean after1 = calendar.getTime().after(now);
                                if (!after1) {
                                    if (byConfigId.getTaskState().equals("待排查")) {
                                        // 推送企业微信

                                        log.info("推送企业微信:{}", JSON.toJSONString(preventionSecurityRisk));


                                        sengwxOne(preventionSecurityRisk);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }


    // @Scheduled(cron = "0/10 * * * * ?")
    @Scheduled(cron = "0/60 * * * * ?")
    public void scheduledConfig() {
        List<PreventionCheckTaskConfig> preventionCheckTaskConfigs = preventionCheckTaskConfigDao.queryAll();
        for (PreventionCheckTaskConfig i : preventionCheckTaskConfigs) {
            PreventionSecurityRisk preventionSecurityRisk = preventionSecurityRiskService.queryById(i.getSecurityRiskId());
            if (null == preventionSecurityRisk) {
                continue;
            }
            PreventionUnit preventionUnit = preventionUnitMapper.queryByDeviceId(preventionSecurityRisk.getDeviceId());
            if (null != preventionUnit && preventionUnit.getState().equals("1")) {
                continue;
            }
            Integer whetherConfig = i.getWhetherConfig();
            // 是否发布
            Integer whetherRelease = i.getWhetherRelease();
            if (whetherConfig == 0 && whetherRelease == 0) {
                String taskStartTime = i.getTaskStartTime();
                DateTime parse = DateUtil.parse(taskStartTime, "yyyy-MM-dd HH:mm:ss");
                Date date = parse.toJdkDate();
                DateTime now = DateUtil.date();
                boolean after = date.after(now);
                if (!after) {
                    if (ObjectUtils.isNotEmpty(preventionSecurityRisk)) {
                        if (StringUtils.isNotEmpty(preventionSecurityRisk.getCycle())) {
                            String cycle = preventionSecurityRisk.getCycle();
                            // 小时 月 天 年
                            String unit = preventionSecurityRisk.getUnit();
                            String startHour = preventionSecurityRisk.getWorkEndTime();
                            String endHour = preventionSecurityRisk.getWorkStartTime();
                            boolean flag = unit.equals("小时");
                            boolean unitFlag = true;
                            if (flag) {
                                if (!compareHHMM(startHour))  { unitFlag = false; }
                                if (StringUtils.isNotEmpty(endHour) && compareHHMM(endHour))  { unitFlag = false; }
                            }

                            PreventionCheckTask byConfigId = preventionCheckTaskService.queryByConfigId(i.getId());
                            PreventionCheckTask preventionCheckTask = new PreventionCheckTask();
                            if (byConfigId == null && (!flag || unitFlag)) {
                                DateTime offset = parse.offset(strUnitDate(unit), Integer.valueOf(cycle));
                                if (i.getIsStartEnd() == 0) {
                                    preventionCheckTask.setTaskState("待排查");
                                } else {
                                    preventionCheckTask.setTaskState("已停用");
                                }
                                preventionCheckTask.setCheckTaskConfigId(i.getId());
                                preventionCheckTask.setStartTime(taskStartTime);
                                preventionCheckTask.setEndTime(offset.toString());
                                preventionCheckTask.setCheckUserName(i.getCheckUserNames());
                                preventionCheckTaskService.insert(preventionCheckTask);
                            } else {
                                String endTime = byConfigId.getEndTime();
                                DateTime dateTime = DateUtil.parse(endTime, "yyyy-MM-dd HH:mm:ss");
                                Date date1 = dateTime.toJdkDate();
                                boolean after1 = date1.after(now);
                                if (!after1) {
                                    if (byConfigId.getTaskState().equals("待排查")) {
                                        byConfigId.setTaskState("已超时");
                                        preventionCheckTaskService.update(byConfigId);
                                        // 推送企业微信
                                        sengwx(preventionSecurityRisk,1);
                                        PreventionAlert preventionAlert = new PreventionAlert();
                                        preventionAlert.setAlertType("隐患排查");
                                        preventionAlert.setAlertLevel(preventionUnit.getDeviceName());
                                        preventionAlert.setAlertInfo("隐患排查任务已超时");
                                        preventionAlert.setAlertTaskUser(preventionSecurityRisk.getDeptUserName());
                                        preventionAlert.setAlertContent(preventionSecurityRisk.getHiddenContent());
                                        preventionAlert.setAlertEndTime(endTime);
                                        preventionAlert.setAlertNoticeState("0");
                                        preventionAlert.setAlertNoticeName("排查逾期推送人员");
                                        preventionAlert.setAlertNoticeMode("企业微信");
                                        preventionAlertMapper.insert(preventionAlert);
                                    }
                                    if (!flag || unitFlag) {
                                        DateTime offset = dateTime.offset(strUnitDate(unit), Integer.valueOf(cycle));
                                        preventionCheckTask.setCheckTaskConfigId(i.getId());
                                        preventionCheckTask.setStartTime(endTime);
                                        preventionCheckTask.setEndTime(offset.toString());
                                        preventionCheckTask.setCheckUserName(i.getCheckUserNames());
                                        preventionCheckTask.setTaskState("待排查");
                                        preventionCheckTaskService.insert(preventionCheckTask);
                                    }
                                } else {
                                    if (byConfigId.getTaskState().equals("待排查")) {
                                        if (!flag) {
                                            String e = byConfigId.getEndTime();
                                            DateTime parse1 = DateUtil.parse(e, "yyyy-MM-dd HH:mm:ss");
                                            DateTime offset = DateUtil.offset(parse1, DateField.DAY_OF_YEAR, -3);
                                            boolean after2 = offset.after(now);
                                            if (after2) {
                                                // 推送企业微信
                                                PreventionAlert preventionAlert = new PreventionAlert();
                                                preventionAlert.setAlertType("隐患排查");
                                                preventionAlert.setAlertLevel(preventionUnit.getDeviceName());
                                                preventionAlert.setAlertInfo("隐患排查任务临近任务结束日期，请尽快完成任务");
                                                preventionAlert.setAlertTaskUser(preventionSecurityRisk.getDeptUserName());
                                                preventionAlert.setAlertContent(preventionSecurityRisk.getHiddenContent());
                                                preventionAlert.setAlertEndTime(endTime);
                                                preventionAlert.setAlertNoticeState("0");
                                                preventionAlert.setAlertNoticeName("排查逾期推送人员");
                                                preventionAlert.setAlertNoticeMode("企业微信");
                                                long count = preventionAlertMapper.count(preventionAlert);
                                                if (count == 0) {
                                                    preventionAlertMapper.insert(preventionAlert);
                                                    sengwx(preventionSecurityRisk,2);
                                                }
                                            }
                                        }
                                    }
                                }
                                if (byConfigId.getTaskState().equals("已排查")) {
                                    String startTime = byConfigId.getStartTime();
                                    DateTime dateStartTime = DateUtil.parse(startTime, "yyyy-MM-dd HH:mm:ss");
                                    Date date2 = dateStartTime.toJdkDate();
                                    boolean after2 = date2.after(date);
                                    if (!after2 && !startTime.equals(taskStartTime)) {
                                        if (!flag || unitFlag) {
                                            DateTime offset2 = parse.offset(strUnitDate(unit), Integer.valueOf(cycle));
                                            PreventionCheckTask preventionCheckTask1 = new PreventionCheckTask();
                                            preventionCheckTask1.setTaskState("待排查");
                                            preventionCheckTask1.setCheckTaskConfigId(i.getId());
                                            preventionCheckTask1.setStartTime(taskStartTime);
                                            preventionCheckTask1.setEndTime(offset2.toString());
                                            preventionCheckTask1.setCheckUserName(i.getCheckUserNames());
                                            preventionCheckTaskService.insert(preventionCheckTask1);
                                        }
                                    }
                                }
                            }
                            if (preventionCheckTask != null && preventionCheckTask.getId() != null) {
                                // 新增待办
                                List<SysActing> sysActings = new ArrayList<>();
                                // 获取任务详情
                                Integer taskId = preventionCheckTask.getId();
                                PreventionCheckTaskVO preventionCheckTaskVO = preventionCheckTaskService.getTaskInfoById(taskId);
                                String checkUserIds = i.getCheckUserIds();
                                String[] ids = checkUserIds.split(",");
                                for (String idStr : ids) {
                                    Long id = Long.parseLong(idStr);
                                    SysUser sysUser = userService.selectUserById(id);
                                    String userName = sysUser.getUserName();
                                    SysActing sysActing = new SysActing();
                                    sysActing.setTitleName("隐患");
                                    sysActing.setTitleType("排查任务");
                                    sysActing.setTitleInfo(preventionCheckTaskVO.getDeviceName());
                                    sysActing.setExecutorName(userName);
                                    sysActing.setExecutorId(id.intValue());
                                    sysActing.setSourceId(taskId);
                                    sysActing.setOriginatorId(preventionCheckTaskVO.getUserId());
                                    sysActing.setOriginatorName(preventionCheckTaskVO.getUserName());
                                    sysActings.add(sysActing);
                                }
                                sysActingService.insertBatch(sysActings);
                            }
                        }
                    }
                }
            }
        }
        ;
    }

    public boolean compareHHMM(String HHMM) {
        if (StringUtils.isEmpty(HHMM)) return true;
        String[] ary = HHMM.split(":");
        // 获取当前时间
        LocalTime now = LocalTime.now();
        // 获取小时
        int hour = now.getHour();
        // 获取分钟
        int minute = now.getMinute();
        if (Integer.parseInt(ary[0]) > hour) {
            return true;
        }
        if (Integer.parseInt(ary[0]) == hour && Integer.parseInt(ary[1])>minute) {
            return true;
        }
        return false;
    }

    @Async
    public void sengwx(PreventionSecurityRisk preventionSecurityRisk,int flag) {
        List<Integer> userIds = sysUserMapper.selectUserByPostName("排查逾期推送");
        // 单元
        String analysisUnit = preventionSecurityRisk.getAnalysisUnit();
        String deptUserName = preventionSecurityRisk.getDeptUserName();
        EnterpriseWXServiceImpl.SendMessageRequest sendMessageRequest = new EnterpriseWXServiceImpl.SendMessageRequest();
        sendMessageRequest.setTouser(CollUtil.join(userIds, "|"));
        sendMessageRequest.setMsgtype("text");
        sendMessageRequest.setAgentid(1000319);
        EnterpriseWXServiceImpl.MessageContent messageContent = new EnterpriseWXServiceImpl.MessageContent();
        if (flag == 2) {
            messageContent.setContent("任务即将逾期预警: " + analysisUnit + "(单元)" + deptUserName + "(岗位责任人)");
        } else {
            messageContent.setContent("任务逾期预警: " + analysisUnit + "(单元)" + deptUserName + "(岗位责任人)");
        }
        sendMessageRequest.setText(messageContent);
        enterpriseWXService.pushMessage(sendMessageRequest);
    }


    @Async
    public void sengwxOne(PreventionSecurityRisk preventionSecurityRisk) {
        List<Integer> userIds = new ArrayList<>();
        // 单元
        String analysisUnit = preventionSecurityRisk.getAnalysisUnit();
        String deptUserName = preventionSecurityRisk.getDeptUserName();
        EnterpriseWXServiceImpl.SendMessageRequest sendMessageRequest = new EnterpriseWXServiceImpl.SendMessageRequest();
        sendMessageRequest.setTouser(CollUtil.join(userIds, "|"));
        sendMessageRequest.setMsgtype("text");
        sendMessageRequest.setAgentid(1000319);
        EnterpriseWXServiceImpl.MessageContent messageContent = new EnterpriseWXServiceImpl.MessageContent();
        messageContent.setContent("任务即将预期预警: " + analysisUnit + "(单元)" + deptUserName + "(岗位责任人)");
        sendMessageRequest.setText(messageContent);
        enterpriseWXService.pushMessage(sendMessageRequest);
    }


    public static DateField strUnitDate(String unit) {
        if (unit.equals("日") || unit.equals("天")) {
            return DateField.DAY_OF_MONTH;
        }
        if (unit.equals("月")) {
            return DateField.MONTH;
        }
        if (unit.equals("小时")) {
            return DateField.HOUR_OF_DAY;
        }
        if (unit.equals("年")) {
            return DateField.YEAR;
        }
        return null;
    }


    @Override
    public List<PreventionCheckTaskCountStateVO> getToCountDept(String checkUserName, String beginDayOfLastWeek, String endDayOfLastWeek) {
        return preventionCheckTaskConfigDao.getToCountDept(checkUserName, beginDayOfLastWeek, endDayOfLastWeek);
    }

    @Override
    public List<PreventionCheckTaskCountStateVO> getToTwoCountDept(String checkUserName, String beginDayOfLastWeek, String endDayOfLastWeek) {
        return preventionCheckTaskConfigDao.getToTwoCountDept(checkUserName, beginDayOfLastWeek, endDayOfLastWeek);
    }

    @Override
    public List<PreventionCheckTaskCountStateVO> getToCountHiddenRate(String checkUserName, String beginDayOfLastWeek, String endDayOfLastWeek) {
        return preventionCheckTaskConfigDao.getToCountHiddenRate(checkUserName, beginDayOfLastWeek, endDayOfLastWeek);
    }

    @Override
    public List<PreventionCheckTaskCountStateVO> getToAllCountHiddenRate(String checkUserName, String beginDayOfLastWeek, String endDayOfLastWeek) {
        return preventionCheckTaskConfigDao.getToAllCountHiddenRate(checkUserName, beginDayOfLastWeek, endDayOfLastWeek);
    }

    @Override
    public List<PreventionCheckTaskCountStateVO> getDeptGroupByList(String checkUserName) {
        return preventionCheckTaskConfigDao.getDeptGroupByList(checkUserName);
    }

    @Override
    public List<PreventionCheckTaskCountStateVO> getCheckAllSituation(String checkUserName) {
        return preventionCheckTaskConfigDao.getCheckAllSituation(checkUserName);
    }

    /**
     * 隐患排查治理__查询部门树结构信息_联动列表
     *
     * @return
     */
    @Override
    public List<PreventionHiddenDeptTreeListVO> getHiddenDeptTreeList(PreventionHiddenDeptTreeListDTO dto) {
        List<PreventionHiddenDeptTreeListVO> list = new ArrayList<>();
        // 根据部门id查询
        SysDept sysDept = sysDeptMapper.selectDeptById(dto.getDeptId());
        if (ObjectUtils.isNotEmpty(sysDept)) {
            List<SysUserVO> sysUsers = sysUserMapper.selectHiddenUserList(dto);
            if (ObjectUtils.isNotEmpty(sysUsers)) {
                // 循环遍历
                for (SysUserVO sysUser : sysUsers) {
                    PreventionHiddenDeptTreeListVO vo = new PreventionHiddenDeptTreeListVO();
                    vo.setDeptId(sysUser.getDeptId());
                    vo.setNickName(sysUser.getNickName());
                    vo.setUserName(sysUser.getUserName());
                    vo.setDeptName(sysUser.getDeptName());
                    vo.setPostName(sysUser.getPostName());
                    // 根据用户昵称 查询任务记录表
                    //String  byLimitCount= preventionCheckTaskMapper.queryAllByLimitCount(sysUser.getNickName());
                    String byLimitCount = preventionCheckTaskConfigDao.queryAllByLimitCount(sysUser.getNickName());
                    if (StringUtils.isNotEmpty(byLimitCount)) {
                        vo.setCountTask(byLimitCount);
                    }
                    list.add(vo);
                }
            }
        }
        return list;
    }


    /**
     * 隐患排查治理_排查任务记录_刷新任务
     *
     * @param dto
     * @return
     */
    @Override
    public PreventionCheckTaskConfigVO updateRefresh(PreventionCheckTaskConfigRefreshDTO dto) {
        PreventionCheckTaskConfigVO vo = new PreventionCheckTaskConfigVO();
        if (ObjectUtils.isNotEmpty(dto)) {
            // 根据securityRiskId 查询风险分析清单表
            PreventionCheckTaskConfig preventionCheckTaskConfig = preventionCheckTaskConfigDao.queryById(dto.getId());
            PreventionCheckTask preventionCheckTask = preventionCheckTaskMapper.queryByConfigId(preventionCheckTaskConfig.getId());
            preventionCheckTask.setCheckUserName(preventionCheckTaskConfig.getCheckUserNames());
            preventionCheckTaskMapper.update(preventionCheckTask);
        }
        return vo;
    }

    @Override
    public List<PreventionCheckTaskConfigExportVO> export(PreventionCheckTaskConfigVO preventionCheckTaskConfigVO) {
        return preventionCheckTaskConfigDao.export(preventionCheckTaskConfigVO);
    }


}
